package com.synergy.stockflow.sales.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.synergy.stockflow.entity.SysUser;
import com.synergy.stockflow.model.Result;
import com.synergy.stockflow.sales.entity.CustomerResources;
import com.synergy.stockflow.sales.service.CustomerResourcesService;
import com.synergy.stockflow.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/CustomerResources")
public class CustomerResourcesController {
    @Autowired
    CustomerResourcesService customerResourcesService;

    @Autowired
    SysUserService sysUserService;

    @GetMapping
    public Result<Page<CustomerResources>> getCustomerResources(
            @RequestParam(name = "current", defaultValue = "1") int current,
            @RequestParam(name = "size", defaultValue = "5") int size,
            @RequestParam(name = "customerResourcesName", required = false) String customerResourcesName,
            @RequestParam(name = "customerResourcesId", required = false) Integer customerResourcesId,
            @RequestParam(name = "customerResourcesContactPhone", required = false) String customerResourcesContactPhone,
            @RequestParam(name = "customerResourcesCustomerSegmentation", required = false) String customerResourcesCustomerSegmentation) {

        Page<CustomerResources> page = new Page<>(current, size);
        page = customerResourcesService.getCustomerResources(page, customerResourcesName, customerResourcesId, customerResourcesContactPhone, customerResourcesCustomerSegmentation);
        for(CustomerResources customerResources : page.getRecords()){
            LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
            customerResources.setNickname(sysUserService.getOne(queryWrapper.eq(SysUser::getId, customerResources.getCustomerResourcesHeadOfSales())).getNickname());
        }
        return Result.success(page);
    }

    @PostMapping
    public Result insert(@RequestBody CustomerResources customerResources) {
        customerResourcesService.save(customerResources);
        return Result.success(customerResources);
    }
    @PutMapping
    public Result update(@RequestBody CustomerResources customerResources) {
        customerResourcesService.updateById(customerResources);
        return Result.success(customerResources);
    }
    @DeleteMapping
    public Result delete(@RequestBody List<CustomerResources> customerResource) {
        for(CustomerResources c : customerResource) {
            customerResourcesService.removeById(c.getCustomerResourcesId());
        }
        return Result.success(customerResource);
    }
}
